<script setup>
import { getQuery, getTopLevelDomain, toQuery } from '@/common/utils';
import { debounce } from 'lodash';
import { closeToast, showToast } from 'vant';
import { onBeforeUnmount, onMounted } from 'vue';

const _BeylaCls = window._BeylaCls;
let baseUrl = '';

const props = defineProps(['class', 'game']);
const { class: className, game = {} } = props;

const hostInit = () => {
  const topLevDomain = getTopLevelDomain();
  const allDomain = getTopLevelDomain('all');
  if (topLevDomain === allDomain) {
    baseUrl = `https://game.${topLevDomain}`;
  } else {
    baseUrl = `https://game-${allDomain}`;
  }
};

const handleGameEnter = debounce(
  function () {
    const { url } = game;
    const gameUrl = `${baseUrl}${url}?${toQuery(getQuery().query)}`;

    window.location.href = gameUrl;
    _BeylaCls?.gameClickReport(game);

    showToast({
      type: 'loading',
      overlay: true,
      forbidClick: true,
      duration: 4000,
      overlayStyle: { background: 'rgba(0,0,0,.3)' },
      className: 'loading-dialog',
    });
  },
  2000,
  { leading: true, trailing: false },
);

onMounted(() => {
  hostInit();

  window.addEventListener('beforeunload', () => {
    closeToast(true);
  });
});
onBeforeUnmount(() => {
  closeToast(true);
});
</script>
<template>
  <div :class="className" @click="handleGameEnter" :data-log="_BeylaCls?.logShowVe(game)">
    <van-image class="game-img" lazy-load :src="game.icon" :alt="game.name">
      <template v-slot:loading>
        <van-loading type="spinner" size="20" />
      </template>
    </van-image>
  </div>
</template>
<style lang="scss">
.game-img {
  width: 100%;
  height: 100%;
  border-radius: 12px;
  overflow: hidden;
}
</style>
